# -*- coding: utf-8 -*-

#	This file is part of Kanji-Notification.

#	Kanji-Notification is free software: you can redistribute it 
#	and/or modify it under the terms of the GNU General Public License 
#	as published by the Free Software Foundation, either version 3 of 
#	the License, or	(at your option) any later version.
#
#	Kanji-Notification is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with Kanji-Notification. If not, see <http://www.gnu.org/licenses/>.

import gtk.gdk
import cairo
import random
import pango
import os
import pynotify
from kn_parser import parse_xml
from time import sleep

def draw_kanji(kanji, font):
	width, height = 256, 256
	# create the surface and context
	pixmap = gtk.gdk.Pixmap (None, width, height, 24)
	context = pixmap.cairo_create ()
	# white background
	context.set_source_rgb( 1, 1, 1)
	context.rectangle( 0, 0, width, height)
	context.fill()
	# text properties
	context.set_font_size( 256)
	context.select_font_face(font)
	context.move_to( 0, 220)
	context.set_source_rgb( 0, 0, 0)
	# write the text
	context.show_text(kanji)
	# finalization
	context.show_page()
	pixbuf = gtk.gdk.Pixbuf (gtk.gdk.COLORSPACE_RGB, True, 8, width, height)
	pixbuf = pixbuf.get_from_drawable (pixmap, gtk.gdk.colormap_get_system(), 0, 0, 0, 0,  width, height)
	return pixbuf
def main():
	if not pynotify.init("KanjiNotification"):
		sys.exit(1)
	file_name = "kanji.xml"
	root = parse_xml(file_name)
	modification_time  = os.path.getmtime(file_name)
	while True:
		kanji = random.choice(root.kanji)
		pix = draw_kanji(kanji.uchar,root.fontName)
		msg = "Kun: " + " , ".join(kanji.kun) + "\n"
		msg += "On: " + " , ".join(kanji.on) + "\n"
		msg += "Examples:\n"
		msg += "\n".join([aux.__unicode__() for aux in kanji.examples])
		notification = pynotify.Notification(kanji.uchar, msg)
		notification.set_icon_from_pixbuf(pix)
		if not notification.show():
			print "Failed to send notification"
			sys.exit(1)
		sleep(root.sleep)
		#Check if file was modified. If it was modified we need to parse it
		#again
		aux = os.path.getmtime(file_name)
		if (aux > modification_time):
			modification_time = aux
			root = parse_xml(file_name)
		
if __name__ == "__main__":
	main()
